import React, {memo, useEffect} from "react";
import './index.scss'
import {renderRoutes} from "react-router-config";
import {connect} from "react-redux";
import {getShopData} from "@/common/store/modules/shop";
import {useHistory} from "react-router-dom";
import Swiper from 'swiper'
import 'swiper/css/swiper.min.css'
import Scroll from "@/components/scroll";
import {IShop} from "@/common/model";

const Shop: React.FC<any> = (props) => {
  console.log("-------Shop------")

  const subRoutes = props.route.routes

  // state
  const {shopdata} = props
  // action
  const {getShopDataDispatch} = props

  const TZONE: IShop[] = shopdata.TZONE ? shopdata.TZONE : []

  const history = useHistory()

  const goDetail = (item: any) => {
    history.push({pathname: `/shop/teslaZone/${item.id}`, state: item})
  }

  const goShop = () => {
    history.push({pathname: '/shop/teslaShop', state: shopdata.goods})
  }

  useEffect(() => {
    console.log(shopdata.length)
    if (!shopdata.length) {
      getShopDataDispatch()
    }
  }, [])

  useEffect(() => {
    // 防止刷新swiper样式丢失
    setTimeout(() => {
      new Swiper('.swiper-container', {
        slidesPerView: 'auto',
        centeredSlides: true,
        spaceBetween: 20
      });
    }, 100)
  }, [])

  return (
    <div className="main">
      <div className="title">特斯拉Tesla</div>
      <Scroll
        direction="vertical" // 垂直滚动
        refresh={false} // 下拉更新为false
      >
        <div>
          <div className="teslaShop" onClick={() => goShop()}>
            <img alt="" src="https://china-community-app.tesla.cn/wechatmini/shop.png"/>
          </div>
          <div className="swiper-container">
            <p>T - ZONE</p>
            <div className="swiper-wrapper">
              {
                TZONE.map((item, _) => {
                  return (
                    <div key={item.id} className="swiper-slide">
                      <img alt="" src={item.picUrl} onClick={() => goDetail(item)}/>
                    </div>
                  )
                })
              }
            </div>
          </div>
        </div>
      </Scroll>
      {renderRoutes(subRoutes)}
    </div>
  )
}

const mapStateToPorps = (state: any) => {
  return {
    shopdata: state.shop.shopdata
  }
}

function mapDispatchToPorps(dispatch: any) {
  return {
    getShopDataDispatch() {
      dispatch(getShopData())
    }
  }
}

export default connect(mapStateToPorps, mapDispatchToPorps)(memo(Shop))
